<!-- pages/register/index.vue -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '忘记密码',
  },
}
</route>
<template>
  <view>
    <view class="mt-4 profile-info-container">
      <view class="form-card">
        <wd-form ref="formRef" :model="formData" :rules="formRules">
          <wd-cell-group>
            <!-- 手机号输入 -->
            <view class="sex-field">
              <view class="zh-tb-text form-item-width">
                <text>手机账号</text>
                <text>བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་</text>
              </view>
              <view class="flex-1">
                <wd-input
                  prop="phoneNumber"
                  v-model="formData.phoneNumber"
                  :placeholder="showTibetan ? '手机账号(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)' : '手机账号'"
                  class="form-input"
                >
                  <template #suffix>
                    <view
                      v-if="countdown === 0"
                      class="code-btn"
                      :class="{ disabled: countdown > 0 }"
                      @click="sendSmsCode"
                    >
                      <view class="zh-tb-text text-#fff">
                        <text>获取验证码</text>
                        <text style="color: #fff; text-align: center">
                          བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་
                        </text>
                      </view>
                    </view>
                    <!-- <view v-if="countdown === 0" class="code-btn" :class="{ disabled: countdown > 0 }"
                      @click="sendSmsCode">
                      <view class="zh-tb-text text-#fff">
                        <text>获取验证码</text>
                        <text style="color:#fff;text-align: center;">བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་</text>
                      </view>
                    </view> -->
                    <view
                      v-else
                      class="code-btn"
                      :class="{ disabled: countdown > 0 }"
                      @click="sendSmsCode"
                    >
                      <text>{{ countdown }}s后重发</text>
                    </view>
                  </template>
                </wd-input>
              </view>
            </view>
            <!-- 验证码输入 -->
            <view class="sex-field">
              <view class="zh-tb-text form-item-width">
                <text>验证码</text>
                <text>བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་</text>
              </view>
              <view class="flex-1">
                <wd-input
                  prop="code"
                  v-model="formData.code"
                  :placeholder="
                    showTibetan ? '请输入验证码(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)' : '请输入验证码'
                  "
                  class="form-input"
                />
              </view>
            </view>
            <!-- 密码输入 -->
            <!--            <view class="sex-field">
              <view class="zh-tb-text form-item-width">
                <text>密码设置</text>
                <text>བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་</text>
              </view>
              <view class="flex-1">
                <wd-input
                  prop="password"
                  v-model="formData.newPassword"
                  :placeholder="showTibetan ? '请输入密码(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)' : '请输入密码'"
                  show-password
                  class="form-input"
                />
              </view>
            </view> -->
            <!-- 确认密码 -->
            <!--            <view class="sex-field">
              <view class="zh-tb-text form-item-width">
                <text>确认密码</text>
                <text>བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་</text>
              </view>
              <view class="flex-1">
                <wd-input
                  prop="confirmPassword"
                  v-model="formData.confirmPassword"
                  :placeholder="showTibetan ? '确认密码(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)' : '确认密码'"
                  show-password
                  class="form-input"
                />
              </view>
            </view> -->
          </wd-cell-group>
        </wd-form>

        <!-- 忘记密码按钮 -->
        <view class="mt-4 flex justify-center">
          <wd-button
            type="error"
            size="large"
            @click="handleResetPassword"
            custom-class="custom-shadow"
            customStyle=" width: 60vw; height: 6vh "
          >
            <view class="zh-tb-text text-#fff">
              <text>提交忘记密码申请</text>
              <text style="color: #fff">བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་</text>
            </view>
          </wd-button>
        </view>
      </view>
    </view>
    <CaptchaPopup ref="captchaRef" @success="onCaptchaSuccess" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { forgetPasswordApplication } from '@/api/login'
import { getCode } from '@/api/login'
import CaptchaPopup from '@/pages/login/CaptchaPopup.vue'
import { toast, showToastAsync } from '@/utils/toast'
// import { sendSmsCode } from '@/api/sms'

const showTibetan = import.meta.env.VITE_SHOW_TIBETAN === 'true'
const globalConfig = getApp().globalData.config
const countdown = ref(0)
const agreed = ref(false)
const formRef = ref()
const captchaRef = ref()

// 表单数据
const formData = reactive({
  phoneNumber: '',
  code: '',
  newPassword: '',
  confirmPassword: '',
  uuid: undefined,
  // userName: ''
})

// 验证规则
const formRules: any = {
  phoneNumber: [
    { required: true, message: '手机账号', trigger: ['blur', 'change'] },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: ['blur', 'change'],
    },
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: ['blur', 'change'],
    },
    // {
    //   validator: (value: string) => {
    //     return /^\d{4}$/.test(value)
    //       ? Promise.resolve()
    //       : Promise.reject('验证码必须为4位数字')
    //   },
    //   trigger: ['blur', 'change'],
    // },
  ],
  newPassword: [
    {
      required: true,
      message: '请输入密码',
      trigger: ['blur', 'change'],
    },
    // 正则判断为字母或数字
    // {
    //   pattern: /^[0-9a-zA-Z]*$/g,
    //   // 正则检验前先将值转为字符串
    //   transform(value: any) {
    //     return String(value)
    //   },
    //   message: '只能包含字母或数字',
    // },
    {
      validator: (value: any) => {
        if (value.length >= 5 && value.length <= 12) {
          return Promise.resolve()
        } else {
          return Promise.reject('密码长度必须在5到12位之间')
        }
      },
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    { required: true, message: '确认密码', trigger: ['blur', 'change'] },
    // 正则判断为字母或数字
    {
      pattern: /^[0-9a-zA-Z]*$/g,
      // 正则检验前先将值转为字符串
      transform(value: any) {
        return String(value)
      },
      message: '只能包含字母或数字',
    },
    {
      validator: (value: any) => {
        if (value.length >= 5 && value.length <= 12) {
          return Promise.resolve()
        } else {
          return Promise.reject('密码长度必须在5到12位之间')
        }
      },
      trigger: 'blur',
    },
    {
      validator: (value: string) => value === formData.newPassword,
      message: '两次密码输入不一致',
      trigger: ['blur', 'change'],
    },
  ],
  // userName: [
  //     { required: true, message: '请输入姓名(བོད་ཀྱི་སྐད་བོད་ཀྱི་སྐད་)', trigger: ['blur', 'change'] },
  //     { min: 2, max: 12, message: '昵称长度2-12位' }
  // ]
}
// 发送验证码
// const sendSmsCode = async () => {
//   try {
//     if (countdown.value > 0) return

//     // await sendSmsCode({
//     //   mobile: formData.mobile,
//     //   scene: 'REGISTER'
//     // })

//     // 开始倒计时
//     countdown.value = 60
//     const timer = setInterval(() => {
//       countdown.value--
//       if (countdown.value <= 0) clearInterval(timer)
//     }, 1000)
//   } catch (error) {
//     uni.showToast({ title: '验证码发送失败', icon: 'none' })
//   }
// }
//没有短信服务，临时方案
const sendSmsCode = async () => {
  const res = await getCode()
  const imageBase64 = res.data?.img
  const uuid = res.data?.uuid
  console.log('uuid', uuid)

  // 弹出验证码弹窗
  if (captchaRef.value) {
    console.log('进来了吗')
    captchaRef.value.open('data:image/png;base64,' + imageBase64, uuid)
  }
}
const onCaptchaSuccess = async ({ code, uuid }) => {
  formData.code = code
  formData.uuid = uuid
}
const handleResetPassword = async () => {
  try {
    // 表单校验
    const { valid, errors } = await formRef.value.validate()
    if (!valid) {
      console.log('表单校验未通过:', errors)
      return // ✅ 校验失败，终止后续代码
    }
    console.log('formData', formData)
    uni.showLoading({
      title: '提交申请中...',
      mask: true, // 关键：蒙版禁止页面交互
    })
    const res: any = await forgetPasswordApplication(formData)
    if (res.code === 0) {
      await showToastAsync('提交申请成功，请等待管理员与您联系', 1500)
      uni.navigateBack()
    } else {
      await showToastAsync(res.msg || '提交申请失败,请重试', 1500, 'none')
    }
  } catch (error) {
    console.error('申请异常:', error)
    toast.error('申请异常，请稍后再试')
  } finally {
    // 7. 无论成功/失败，关闭加载（必须执行）
    uni.hideLoading()
  }
}
</script>

<style lang="scss" scoped>
.profile-info-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 30rpx;
}

.form-card {
  background-color: #fff;
  border-radius: 20rpx;
  // margin: auto;
  // width: 90%;
  padding: 40rpx 20rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.form-border {
  overflow: hidden;
  border: 2rpx solid #eee;
  border-radius: 50rpx;
  margin: 30rpx 0;
  padding: 0 10rpx;
}

.sex-field {
  display: flex;
  align-items: center;
  padding: 24rpx 10rpx;
  background-color: #ffffff;
}

.code-btn {
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  padding: 10rpx;
  background-color: #f93d3d;
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 1.2;
  text-align: left;

  &.disabled {
    color: #fff;
  }

  text:nth-child(2) {
    /* 第二个 span，藏文 */
    // color: #333;
    font-size: 20rpx;
  }
}

.protocol-box {
  display: flex;
  align-items: center;
  margin: 30rpx 0;
  padding: 0 10rpx;

  .protocol-text {
    color: #000;
    margin-left: 5rpx;
  }
}

.login-link {
  text-align: center;
  margin-top: 40rpx;
  color: #666;

  text:last-child {
    color: red;
    margin-left: 20rpx;
  }
}
</style>
